import Taro from "@tarojs/taro";
import { trackPerformance } from "./tracking";

// 性能监控指标
const performanceMetrics = {
  pageLoadTime: 0, // 页面加载时间
  firstPaintTime: 0, // 首次渲染时间
  domReadyTime: 0, // DOM准备时间
  networkTime: 0, // 网络请求时间
  resourceLoadTime: 0, // 资源加载时间
};

// 初始化性能监控
export const initPerformanceMonitor = () => {
  // 监听页面加载
  Taro.onAppRoute((res) => {
    const startTime = Date.now();

    // 页面加载完成
    Taro.nextTick(() => {
      const endTime = Date.now();
      performanceMetrics.pageLoadTime = endTime - startTime;

      // 记录性能数据
      trackPerformance({
        ...performanceMetrics,
        pagePath: res.path,
        timestamp: Date.now(),
      });
    });
  });

  // 监听网络请求
  Taro.addInterceptor(Taro.interceptors.logInterceptor);
  Taro.addInterceptor((chain) => {
    const requestParams = chain.requestParams;
    const startTime = Date.now();

    return chain.proceed(requestParams).then((res) => {
      const endTime = Date.now();
      performanceMetrics.networkTime = endTime - startTime;

      // 记录网络请求性能
      trackPerformance({
        ...performanceMetrics,
        requestUrl: requestParams.url,
        requestMethod: requestParams.method,
        responseStatus: res.statusCode,
        timestamp: Date.now(),
      });

      return res;
    });
  });
};

// 获取性能指标
export const getPerformanceMetrics = () => {
  return { ...performanceMetrics };
};

// 重置性能指标
export const resetPerformanceMetrics = () => {
  Object.keys(performanceMetrics).forEach((key) => {
    performanceMetrics[key] = 0;
  });
};
